package com.yintao.ytframe.nosql.redis;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author yintao
 * @desc 写清楚这个类的作用
 * @package com.yintao.ytframe.nosql.redis
 * @date 2021/8/614:44
 */
@Component
public class RedisUtil {

    @Autowired
    RedisTemplate<String,Object> redisTemplate;

    public void set(String key,Object object){
        if(StrUtil.isEmptyIfStr(key)){
            return;
        }
        redisTemplate.opsForValue().set(key,object);
    }

    public void setEx(String key,Object object,TimeUnit timeUnit,Long timeout){
        if(StrUtil.isEmptyIfStr(key)){
            return;
        }
        redisTemplate.opsForValue().set(key,object);
        expire(key,timeUnit,timeout);
    }

    public String getStr(String key){
        Object value = redisTemplate.opsForValue().get(key);
        if(value instanceof String){
            return (String)value;
        }
        return JSONUtil.toJsonStr(value);
    }

    public Object get(String key){
        return redisTemplate.opsForValue().get(key);
    }

    public void expire(String key, TimeUnit timeUnit,Long timeout){
        redisTemplate.expire(key,timeout,timeUnit);
    }


}
